<template>
  <div v-if="show" id="notice">
    <div>由于您长时间没有操作，系统将在
      <span v-html="noticeTime/1000"></span>秒后即将返回首页，关闭界面取消</div>
    <button @click="resetTimer">关闭界面</button>
  </div>
</template>

<script>
export default {
  data() {
    return {
      show: true,
      // maxTime: 2 * 60 * 1000,
      maxTime: 10 * 1000,
      noticeTime: 10 * 1000,
      timerIdx1: 0,
      timerIdx2: 0
    }
  },
  mounted() {
    this.listenBody()
  },
  methods: {
    showNotice() {
      this.show = true
      this.noticeTime = 10 * 1000
      let that = this
      this.timerIdx2 = setInterval(function() {
        that.noticeTime = that.noticeTime - 1000
        console.log(that.noticeTime)
        if (that.noticeTime <= 0) {
          clearInterval(that.timerIdx2)
          that.returnHome()
        }
      }, 1000)
    },

    returnHome() {
      this.$router.push('/')
    },

    resetTimer(event) {
      this.show = false
      if (this.timerIdx1) {
        clearTimeout(this.timerIdx1)
      }
      if (this.timerIdx2) {
        clearTimeout(this.timerIdx2)
      }
      this.timerIdx1 = setTimeout(this.showNotice, this.maxTime)
      console.log(this.timerIdx1)
    },
    listenBody() {
      this.resetTimer()
      window.addEventListener('mousedown', this.resetTimer)
      window.addEventListener('keydown', this.resetTimer)
      window.addEventListener('click', this.resetTimer)
      window.addEventListener('touchmove', this.resetTimer)
      window.addEventListener('touchstart', this.resetTimer)
    }
  }
}
</script>

<style scoped>
#notice {
  width: 250px;
  height: 150px;
  position: fixed;
  top: 20%;
  left: 30%;
  background-color: #efefef;
  border: 1px solid white;
  text-align: center;
  border-radius: 5px;
}

#notice div {
  background-color: #efefef;
  height: 60%;
  margin: 0 auto;
  padding: 10px;
}

button {
  margin: 0 auto;
}

span {
  color: red;
}
</style>
